﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DNSChanger
{
    public partial class Form1 : Form
    {
        private int index = -1;
        private NetworkInterface[] nics;

        private Dictionary<string, string[]> nsservers = new Dictionary<string, string[]>
        {
            ["baidu"] =  new string[]{ "180.76.76.76" ,""},
            ["ali"] = new string[] { "223.5.5.5","223.6.6.6"},
            ["tx"] = new string[] { "119.29.29.29","182.254.116.116"},
            ["114"] = new string[] { "114.114.114.114","114.114.115.115"}
        }; 
        public Form1()
        {
            InitializeComponent();
            FindAdapters();
        }
        // 遍历系统网卡
        public void FindAdapters()
        {
            nics = NetworkInterface
                .GetAllNetworkInterfaces()
                .Where(
                nic => nic.OperationalStatus == OperationalStatus.Up 
                && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback
                ).ToArray();
            NSelect.Items.Clear();
            foreach (NetworkInterface nic in nics) { 
                NSelect.Items.Add(nic.Name);
            }
            if (nics.Length > 0) {
                index = 0;
                NSelect.SelectedIndex = index;
                ShowAdapterInfo(nics[index]);
            }

        }
        // 显示网卡的信息
        public void ShowAdapterInfo(NetworkInterface nic)
        {
            TXT_Info.Text = string.Empty;
            TXT_Info.AppendText($"名称:{nic.Name}\r\n");
            string ip = GetDefaultIp(nic);
            TXT_Info.AppendText($"IP:{ip}\r\n");
            var dnss = GetDns(nic);
            for (int i = 0; i < dnss.Count; i++) {
                TXT_Info.AppendText($"DNS{i+1}:{dnss[i]}\r\n");
            }
        }
        // 获取网卡默认ipv4 地址
        public string GetDefaultIp(NetworkInterface nic)
        {
            string ip = string.Empty;
            ip= nic.GetIPProperties().UnicastAddresses
                .Where(
                ipv=>ipv.Address.AddressFamily== System.Net.Sockets.AddressFamily.InterNetwork
                ).FirstOrDefault().Address.ToString();

            return ip;
        }
        // 获取DNS
        public List<string> GetDns(NetworkInterface nic)
        {
            var n=new List<string>();
            var ppp = nic.GetIPProperties();
            var dnss=ppp.DnsAddresses.Where(dns=>dns.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray();
            foreach (var dns in dnss)
            {
                n.Add(dns.ToString());
            }
            return n;
        }
        // 设置网卡的dns
        public void SetDns(NetworkInterface adapter) {
            string s = string.Empty;
            if (RB_Baidu.Checked)
            {
                s = "baidu";
            }
            else if (RB_Ali.Checked)
            {
                s = "ali";
            }
            else if (RB_Tx.Checked)
            {
                s = "tx";
            }
            else {
                s = "114";
            }
            try
            {
                SetDnsManually(adapter, nsservers[s][0], nsservers[s][1]);
                MessageBox.Show("设置dns成功");
                FindAdapters();
                ShowAdapterInfo(nics[index]);
            }
            catch (Exception ex) { 
                MessageBox.Show(ex.Message);
            }
            
        }
        static void SetDnsManually(NetworkInterface adapter, string primaryDns, string secondaryDns)
        {
            try
            {
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"])
                    {
                        if (mo["Description"].ToString() == adapter.Description)
                        {
                            // 准备DNS服务器数组
                            string[] dnsServers;
                            if (string.IsNullOrEmpty(secondaryDns))
                            {
                                dnsServers = new string[] { primaryDns };
                            }
                            else
                            {
                                dnsServers = new string[] { primaryDns, secondaryDns };
                            }

                            // 设置DNS
                            ManagementBaseObject inParams = mo.GetMethodParameters("SetDNSServerSearchOrder");
                            inParams["DNSServerSearchOrder"] = dnsServers;

                            ManagementBaseObject outParams = mo.InvokeMethod("SetDNSServerSearchOrder", inParams, null);
                            Console.WriteLine("返回值: " + outParams["ReturnValue"]);

                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("设置DNS时出错: " + ex.Message);
            }
        }
private void NSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            index= NSelect.SelectedIndex;
            if (index >= 0) {
                ShowAdapterInfo(nics[index]);
            }
            
        }

        private void BTN_OK_Click(object sender, EventArgs e)
        {
            if (index >= 0)
            {
                SetDns(nics[index]);
            }
            else {
                MessageBox.Show("请选择网卡");
            }
        }
    }
    
}
